using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using vs.Core;


using vs.Authentication;

namespace Forum
{
    public partial class reply_edit : UserControl
    {
        private void RegistJavascriptEditor()
        {
            SmileController smile = new SmileController();

            string jsInsertSmile = smile.js_insert_smilie(txtContent.ClientID);
            Page.ClientScript.RegisterClientScriptBlock(typeof(string), "jsInsertSmile", jsInsertSmile);
            lblSmilies.Text = smile.list_images_smilies();

            string jsInsertEditor = smile.js_insert_editor(txtContent.ClientID);
            Page.ClientScript.RegisterClientScriptBlock(typeof(string), "jsInsertEditor", jsInsertEditor);
            lblEditor.Text = smile.list_images_editor();
        }

        private bool HaveRight(string replyID)
        {
            User usr = Authenticate.CurrentUser;
            if(usr != null) if (usr.IsSuperAdmin || usr.Staff) return true;

            string strSQL = "select UserName from FORUM_Reply where ReplyID = @ReplyID";
            DataParameter p = new DataParameter("@ReplyID", replyID);
            object o = DataFactory.ExecuteScalar(strSQL, p);
            if (o != null)
                return (o.ToString() == System.Web.HttpContext.Current.User.Identity.Name);

            return false;
        }

        private void RegisterScriptIMG()
        {
            string js = @"
<script language=javascript>
    function popup2 (name,width,height) { 
         var options = ""toolbar=1,location=1,directories=1,status=1,menubar=1,scrollbars=1,resizable=1, width=""+width+"",height=""+height; 
         Cal2=window.open(name,""popup"",options); 
    }

    function SetImage(val)
    {
        val = '[img]' + val + '[/img]';
        var content = document.getElementById('" + txtContent.ClientID + @"');
        if (content.createTextRange && content.caretPos){
            var caretPos = content.caretPos;
            caretPos.text = caretPos.text.charAt(caretPos.text.length - 1) == ' ' ? val + ' ' : val;
        } else { content.value += val; }
        content.focus();
    }
</script>
";

            lnkInsertImage.Visible = true;
            Page.ClientScript.RegisterClientScriptBlock(typeof(string), "setvalue", js);
            string popup = ResolveUrl("~/portal/Galery/ImageGalery.aspx");
            lnkInsertImage.NavigateUrl = "javascript:popup2('" + popup + "', 500, 400);";
        }

        private void LoadStaffList()
        {
            if (Authenticate.IsEditor)
            {
                btnChangeUser.Visible = true;
                ddlStaff.Visible = true;
                UserDB.FillStaff(ddlStaff);
                RegisterScriptIMG();
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            //throw new Exception("The method or operation is not implemented.");
            try
            {
                if (!Page.IsPostBack)
                {
                    if(Request.IsAuthenticated) LoadStaffList();
                    this.ViewState.Add("url", Request.UrlReferrer.PathAndQuery);
                    string replyID = Request.QueryString["ID"];

                    if (!System.Web.HttpContext.Current.User.Identity.IsAuthenticated)
                        Response.Redirect(UrlProvider.HomeUrl);

                    if (!HaveRight(replyID)) return;

                    engine_forum engine = new engine_forum();
                    txtContent.Text = engine.ReplyContent(replyID);
                    btnDelete.Attributes["onclick"] = "if(!confirm('Ban co chac chan xoa?')) {return false;};";
                    btnChangeUser.Attributes["onclick"] = "if(!confirm('Ban co chac chan muon doi nguoi khong?')) {return false;};";

                    RegistJavascriptEditor();
                }
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
            }
        }

        private bool validating()
        {
            txtContent.Text = Utils.KillScript(txtContent.Text);

            if (txtContent.Text.Trim() == "")
            {
                Response.Write("You have to write anything!");
                return false;
            }

            return true;
        }

        protected void btnReply_Click(object sender, EventArgs e)
        {
            try
            {
                if (!validating()) return;

                engine_forum engine = new engine_forum();
                int replyID = Convert.ToInt32(Request.QueryString["ID"]);
                string username = System.Web.HttpContext.Current.User.Identity.Name;
                engine.UpdateReplyContent(replyID, txtContent.Text.Trim(), username);
                string url = this.ViewState["url"].ToString();

                int topicID = engine.TopicID(replyID);
                string prefix = engine_xml.REPLY_LIST_CACHE_PREFIX + "_" + topicID.ToString();
                DataCache.ResetPrefix(prefix);
                DataCache.RemoveCache(topic_lastest.CACHE_LATEST_TOPIC);

                Response.Redirect(url);
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
            }
        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            try
            {
                engine_forum engine = new engine_forum();
                int replyID = Convert.ToInt32(Request.QueryString["ID"]);

                engine.DeleteReply(replyID);
                int topicID = engine.TopicID(replyID);
               
                string modid = PortalUtils.CurrentModuleID;
                ModSettingController db = new ModSettingController();
                string topicdesk = db.Load(modid, "topicdesk");

                string prefix = engine_xml.REPLY_LIST_CACHE_PREFIX + "_" + topicID.ToString();
                DataCache.ResetPrefix(prefix);
                DataCache.RemoveCache(topic_lastest.CACHE_LATEST_TOPIC);

                string url = UrlProvider.DesktopUrl(topicdesk, topicID.ToString());
                Response.Redirect(url);
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
            }
        }

        protected void btnChangeUser_Click(object sender, EventArgs e)
        {
            try
            {
                int replyID = Convert.ToInt32(Request.QueryString["ID"]);
                string strSQL = "UPDATE Forum_Reply Set UserName='" + ddlStaff.SelectedValue + "' WHERE ReplyID=" + replyID;
                DataFactory.Execute(strSQL);

                engine_forum engine = new engine_forum();
                int topicID = engine.TopicID(replyID);
                string modid = PortalUtils.CurrentModuleID;
                ModSettingController db = new ModSettingController();
                string topicdesk = db.Load(modid, "topicdesk");

                string prefix = engine_xml.REPLY_LIST_CACHE_PREFIX + "_" + topicID.ToString();
                DataCache.ResetPrefix(prefix);

                string url = UrlProvider.DesktopUrl(topicdesk, topicID.ToString());
                Response.Redirect(url);
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
            }
        }
    }
}
